﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace DAO
{
    public class BaseDbContext : DbContext
    {
        /// <summary>
        /// 连接字符串配置,正式使用配置文件获取
        /// </summary>
        private static string connectionConfigStr = "server=.;database=Demo;uid=sa;pwd=123456;";

        /// <summary>
        /// 日志工厂
        /// </summary>
        private static ILoggerFactory efLogger = LoggerFactory.Create(builder =>
          {
              builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                     .AddConsole()//添加引用Microsoft.Extensions.Logging.Console，需要程序以控制台应用启动
                     .AddDebug();//添加引用Microsoft.Extensions.Logging.Debug,输出窗口查看
        });

        public BaseDbContext()
        {
        }

        /// <summary>
        /// 依赖注入数据库连接字符串
        /// </summary>
        /// <param name="options"></param>
        public BaseDbContext(DbContextOptions<DataDBContext> options)
            : base(options)
        {
        }

        /// <summary>
        /// 上下文直接初始化数据库连接字符串，可直接new实例
        /// </summary>
        /// <param name="optionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(connectionConfigStr)//使用SqlServer，引用Microsoft.EntityFrameworkCore.SqlServer
                          .UseLoggerFactory(efLogger);//添加日志打印sql语句
        }
    }
}